package cn.lopr.im.api.controller;

import cn.lopr.im.api.common.CallbackMessage;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController {
    List<String> suffix = new ArrayList<String>() {{
        add("png");
        add("jpg");
    }};

    @RequestMapping("/fileUpload")
    @ResponseBody
    public CallbackMessage<?> fileUpload(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) {
        if (file.isEmpty()) {
            System.out.println("文件为空空");
        }
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));

        for (String s : suffix) {
            if (suffixName.equals(s)) {
                return null;
            }
        }

        String path = this.getClass().getResource("/").getPath() + "upload";
        fileName = UUID.randomUUID() + suffixName;

        File dest = new File(path + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return CallbackMessage.createBySuccess();
    }

    @RequestMapping("/getPath")
    public void getPath() {
        String path = this.getClass().getResource("/").getPath();
        System.out.println();
        File file = new File(path + "/upload");
        System.out.println(file);

    }
}
